import { useMemo, useState } from 'react';
import { OBJExporter } from 'three-legacy/examples/jsm/exporters/OBJExporter';

import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { httpApi, wsApi } from '@app-cad/server';
import { RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';

import {
  ConditionalItem,
  featureFilteredArray,
  getQueryParam,
  QueryParamKeys,
} from '@amcax/base';
import { ctx2 } from '@app-cad/module';
// import { useCommand } from '@app-cad/common/hooks/useCommand';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { httpApi as serverHttpApi } from '@app-cad/server';
import { omitBy } from 'lodash';
import './index.scss';

const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
interface ExportDialogProps {
  title: string;
  onClose: () => void;
}

export function ExportDialog({ title, onClose }: ExportDialogProps) {
  const [btnLoading, setBtnLoading] = useState(false);
  const [formData, setFormData] = useState({
    select: 'step',
    lod: 0.01,
    mode: 'features',
    model: [],
  });

  const doExport = async (format: string, lod = 0.01, mode = 'full') => {
    const { data } = await httpApi.getExportPath(documentId, formData.select);
    const { path, dl } = data;
    const idArr = formData.model.map((data) => data.idInfo.o);
    const params = {
      t: path,
      o: idArr,
      // o: selectedData.map(getIdOfPickedObj),
      lod,
      mode,
    };
    if (format === 'obj') {
      exportObj();
    } else {
      await wsApi.exportModel(params);

      const link = document.createElement('a');
      link.href = dl;
      link.download = ''; // 可以设置下载的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      onClose();
      // window.open(dl);
    }
  };

  const exportAmx = async () => {
    const { data: documentInfo } = await httpApi.getDocumentInfoByUuid();

    const params = {
      collectionId: documentInfo.collectionId,
      documentId: documentInfo.id,
      version: documentInfo.versionDetailResultVo.version,
    };
    try {
      const data = await serverHttpApi.exportAmxFile(params);
      const objData = data?.data;
      const name = documentInfo.name;
      const fileName = `${name ?? documentInfo.id}.amx`;
      const file = new File([objData], fileName, { type: 'application/amx' });
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(file);
      a.href = url;
      a.download = fileName;
      a.click();
      window.URL.revokeObjectURL(a.href);
    } catch {
      MessageTip.error('导出 Amx 文件时出错，请检查网络状况或稍后再试。');
    }
  };

  const exportObj = async () => {
    const { data: documentInfo } = await httpApi.getDocumentInfoByUuid();
    const exporter = new OBJExporter();
    const objData = exporter.parse(ctx2.cadScene.workGroup);
    const blob = new Blob([objData], { type: 'text/plain' });
    const a = document.createElement('a');
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = `${documentInfo.id ?? documentInfo.name}.obj`;
    a.click();
  };

  const handleExecute = async () => {
    setBtnLoading(true);
    if (formData.select === 'amx') {
      await exportAmx();
    } else {
      await doExport(formData.select, formData.lod, formData.mode);
    }
    setBtnLoading(false);
  };
  // useCommand('export', {
  //   onClose,
  //   finishDraw: handleExecute,
  // });

  const schema: RJSFSchema = useMemo(
    () => ({
      type: 'object',
      properties: omitBy(
        {
          select: {
            type: 'string',
            default: 'step',
            title: '请选择导出格式:',
            oneOf: featureFilteredArray([
              {
                title: 'step',
                const: 'step',
              },
              {
                title: 'stl',
                const: 'stl',
              },
              // {
              //   title: 'igs',
              //   const: 'igs',
              // },
              new ConditionalItem('amx-import', {
                title: 'amx',
                const: 'amx',
              }),
              // {
              //   title: 'dxf',
              //   const: 'dxf',
              // },
              // {
              //   title: 'obj',
              //   const: 'obj',
              // },

              // {
              //   title: 'gltf',
              //   const: 'gltf',
              // },
              // {
              //   title: 'brep',
              //   const: 'brep',
              // },
            ]),
          },
          lod: ['obj', 'stl', 'gltf'].includes(formData.select)
            ? {
                type: 'number',
                title: '精度',
              }
            : null,
        } as RJSFSchema,
        (v) => v == null,
      ),
    }),
    [formData.select],
  );

  return (
    <PickableCommandForm
      submitLoading={btnLoading}
      onClose={onClose}
      title={title}
      formData={formData}
      schema={schema}
      submitText='导出'
      onSubmit={handleExecute}
      onChange={(v) => setFormData(v)}
      showCancel={false}
      validator={validator}
      extraUiSchema={{
        format: {
          'ui:placeholder': '请选择导出格式',
        },
        'ui:options': {
          classNames: 'command-form export-dialog',
        },
      }}
    />
  );
}
